package couk.mmtdigital.sm.view
{
	import couk.mmtdigital.sm.ApplicationFacade;
	import couk.mmtdigital.sm.model.FileListProxy;
	import couk.mmtdigital.sm.model.UserProxy;
	import couk.mmtdigital.sm.view.components.FilePanel;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class FilePanelMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "FilePanelMediator";
		
		private var fr:FileReference;
		private var selectedFile:FileReference;
		private var downloadObj:Object;
		
		public function FilePanelMediator(vc:Object=null)
		{
			super(NAME, vc);
			fr = new FileReference();
		}
		
		private function onMkDir(evt:Event):void{
			sendNotification(ApplicationFacade.NEWFOLDER, filePanel.dirNameInput.text);
		}
		
		private function fileButtons(o:Object):void{
			if(o['type'] == 3){
				var fileListProxy:FileListProxy = facade.retrieveProxy(FileListProxy.NAME) as FileListProxy;
				var currentFolder:String = fileListProxy.currentFile;
				var temp:Array = currentFolder.split("/");
				
				trace("folder: "+temp[temp.length-1]+" urlname: "+o['urlname']);
				
				var fileRO:RemoteObject = new RemoteObject("spreadsheetServices");
				fileRO.source = "sm.FileXML";
				fileRO.addEventListener(FaultEvent.FAULT, faultHandler);
				fileRO.getCheckedInValue.addEventListener(ResultEvent.RESULT, resultHandler);
				fileRO.getCheckedInValue(temp[temp.length-1], o['name']); 
			}
		}
		
		//Handler to catch failed connect to the gateway
		private function faultHandler(fault:FaultEvent):void
        {
        	trace("code:\n" + fault.fault.faultCode + "\n\nMessage:\n" + fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail);
        }
        
        private function resultHandler(evt:ResultEvent):void{
        	var userProxy:UserProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
        	if(evt.result['valid'] == 1){
        		filePanel.fileUserLbl.text = evt.result['user'];
        		if(evt.result['checkedInValue'] == 1){
        			filePanel.checkOut.enabled = true;
        			filePanel.checkOut.addEventListener(MouseEvent.CLICK, onCheckOutClick);
        			filePanel.downloadBtn.enabled = true;
        			filePanel.downloadBtn.addEventListener(MouseEvent.CLICK, onDownloadClick);
        		} 
        		else if(evt.result['checkedInValue'] == 0 && evt.result['user'] == userProxy.username){
        			filePanel.checkIn.enabled = true;
        			filePanel.checkIn.addEventListener(MouseEvent.CLICK, onCheckInClick);
        		} 
        	}
        	if(evt.result['valid'] == 0){
        		trace("FAILED");
        	}
        }
        
        private function onCheckInClick(evt:Event):void{
        	trace("onCheckInClick called");
        }
		
		private function onCheckOutClick(evt:Event):void{
			trace("onCheckOutClick called");
			sendNotification(ApplicationFacade.CHECKOUTFILE, downloadObj);
		}
		
		private function onDownloadClick(evt:Event):void{
			trace("onDownloadClick called");
			sendNotification(ApplicationFacade.DOWNLOADFILE, downloadObj);
		}
		
		private function setDownloadObj(o:Object):void{
			var fileListProxy:FileListProxy = facade.retrieveProxy(FileListProxy.NAME) as FileListProxy;
			downloadObj = new Object();
			downloadObj.fileName = o.name; trace(downloadObj.fileName);
			downloadObj.folderName = fileListProxy.currentFile; trace(downloadObj.folderName);
			
		}
		
		//-----------------------file browser
		private function onFileBrowseClick(evt:Event):void{
			fr.addEventListener(Event.SELECT, fileSelectHandler);
			fr.browse(getFilterTypes());
		}
		
		private function onUploadClick(evt:Event):void{
			sendNotification(ApplicationFacade.UPLOADNEWFILE, selectedFile);
		}
		
		private function getFilterTypes():Array{
			var userProxy:UserProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
			return new Array(new FileFilter(userProxy.fileFilterName, userProxy.fileFilter));
		}
		
		private function fileSelectHandler(evt:Event):void{
			selectedFile = FileReference(evt.target);
			trace("fileName: "+selectedFile.name);
			
			filePanel.fileUploadView.uploadBtn.enabled = true;
			fr.removeEventListener(Event.SELECT, fileSelectHandler);
			
			sendNotification(ApplicationFacade.NEWFILE, selectedFile);
		}
		//-----------------------file browser
		
		
		
		override public function listNotificationInterests():Array{
			return [
				ApplicationFacade.FILEPANELNEWFOLDER,
				ApplicationFacade.ONSELECTEDFILE,
				ApplicationFacade.UPLOADVIEW,
				ApplicationFacade.PROGRESSUPDATE,
				ApplicationFacade.LOGGEDOUT
			];
		}
		
		override public function handleNotification(notification:INotification):void{
			switch(notification.getName()){
				case ApplicationFacade.LOGGEDOUT:
					filePanel.currentState = "filePanel";
					break;
				case ApplicationFacade.FILEPANELNEWFOLDER:
					filePanel.currentState = "mkDir";
					filePanel.mkdirBtn.addEventListener(MouseEvent.CLICK, onMkDir);
					break;
				case ApplicationFacade.ONSELECTEDFILE:
					if(filePanel.currentState != "filePanel") filePanel.currentState = "filePanel";
					filePanel.checkIn.enabled = false; filePanel.checkIn.removeEventListener(MouseEvent.CLICK, onCheckInClick);
					filePanel.checkOut.enabled = false; filePanel.checkOut.removeEventListener(MouseEvent.CLICK, onCheckOutClick);
					filePanel.downloadBtn.enabled = false; filePanel.downloadBtn.removeEventListener(MouseEvent.CLICK, onDownloadClick);
					fileButtons(notification.getBody());
					setDownloadObj(notification.getBody());
					break;
				case ApplicationFacade.UPLOADVIEW:
					if(filePanel.currentState != "upload"){
						filePanel.currentState = "upload";
						filePanel.fileUploadView.fbBtn.addEventListener(MouseEvent.CLICK, onFileBrowseClick);
						filePanel.fileUploadView.uploadBtn.addEventListener(MouseEvent.CLICK, onUploadClick);
						facade.registerMediator(new AddFileViewMediator(filePanel.fileUploadView));
						var fileListProxy:FileListProxy = facade.retrieveProxy(FileListProxy.NAME) as FileListProxy;
						var a:Array = fileListProxy.currentFile.split("/");
						filePanel.fileUploadView.destLbl.text = a[a.length-1];
					}
					break;
				case ApplicationFacade.PROGRESSUPDATE:
					var event:ProgressEvent = notification.getBody() as ProgressEvent;
					filePanel.fileUploadView.uploadProgBar.setProgress(event.bytesLoaded, event.bytesTotal);
					break;
				}
			}
			
		private function get filePanel():FilePanel{
			return viewComponent as FilePanel;
		}			
	}
}